/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.sbbs.dao;

import com.googlecode.genericdao.dao.jpa.GenericDAOImpl;
import com.googlecode.genericdao.search.MetadataUtil;
import com.googlecode.genericdao.search.jpa.JPASearchProcessor;
import com.googlecode.genericdao.search.jpa.hibernate.HibernateMetadataUtil;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.List;
import javax.persistence.EntityManager;
import org.hibernate.jpa.internal.EntityManagerFactoryImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Administrator
 */
public abstract class BaseJPADaoImpl<T, ID extends Serializable> extends GenericDAOImpl<T, ID> {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    protected void init(EntityManager em) {
        super.setEntityManager(em);

        MetadataUtil metadataUtil = null;
        try {
            EntityManagerFactoryImpl emf = (EntityManagerFactoryImpl) em.getEntityManagerFactory();
            metadataUtil = com.googlecode.genericdao.search.hibernate.HibernateMetadataUtil.getInstanceForSessionFactory(emf.getSessionFactory());
        } catch (Exception e) {
            metadataUtil = (MetadataUtil) HibernateMetadataUtil.getInstanceForEntityManagerFactory((org.hibernate.ejb.HibernateEntityManagerFactory) em.getEntityManagerFactory());
        }
        JPASearchProcessor searchProcessor = new JPASearchProcessor(metadataUtil);
        super.setSearchProcessor(searchProcessor);
    }

    public boolean exist(ID id) {
        return this._exists(persistentClass, id);
    }

    public void remove(List<T> list) {
        if (list.size() > 0) {
            T[] array = (T[]) Array.newInstance(this.persistentClass, list.size());
            list.toArray(array);
            this.remove(array);
        }
    }

    public abstract T findByStringId(String id);
}
